﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using snat.model;


namespace snat.util {
    public class AdjacencyMatrix : IEnumerable<float>{

        private Dictionary<int, int> nodeLookup;
        private float[,] W;

        public float this[int fromID, int toID] {
            get {
                return W[nodeLookup[fromID], nodeLookup[toID]];
            }
            set {
                W[nodeLookup[fromID], nodeLookup[toID]] = value;
            }
        }

        public float this[BaseNode from, BaseNode to] {
            get {
                return this[from.ID, to.ID];
            }
            set {
                this[from.ID, to.ID] = value;
            }
        }

        public AdjacencyMatrix(bool _noConnections = false) {
            this.nodeLookup = new Dictionary<int, int>();
            int nodePos = 0;
            foreach (BaseNode node in NetworkModel.Instance.Nodes.Values) {
                nodeLookup.Add(node.ID, nodePos++);
            }
            this.W = new float[NetworkModel.Instance.Nodes.Count, NetworkModel.Instance.Nodes.Count];
            for (int i = 0; i < nodeLookup.Count; i++) {
                for (int j = 0; j < nodeLookup.Count; j++) {
                    this.W[i, j] = float.PositiveInfinity;
                }
            }
            if (!_noConnections) {
                foreach (BaseNode from in NetworkModel.Instance.Nodes.Values) {
                    foreach (Edge edge in from.OutEdges) {
                        this[from.ID, edge.Target.ID] = (float)edge.Weight;
                    }
                }
            }
        }

        public bool EdgeExists(BaseNode from, BaseNode to) {
            return !float.IsPositiveInfinity(this[from, to]);
        }


        public IEnumerator<float> GetEnumerator() {
            foreach (float d in W) {
                yield return d;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }
}
